// pages/input_information/index.js
const app = getApp()
import {
  uploadFile
} from '../../api/common.js'
import {
  qualificateData,
  qualificateApply,
  qualificateApplyDetail
} from '../../api/qualificate.js'
import { deepClone } from '../../utils/deepClone.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasSkuQualificate: '', // 类型 0提交 /其它 修改
    qualificateIds: '',
    applyId: '',
    userName: '', // 用户名称
    count: 3, // 图片总数
    imageList: [], // 图片
    imgUrl: [], // 保存后的图片地址
    title: '', // 需要认证指定资质的名称
    remark:'',
    send: true,
    failDesc: '', //失败原因
    matchFormList:[],//需要填写的动态表单列表
    changeDataNow:false//用来存储数据是否在修改状态，避免修改未结束确认按钮就已点击造成验证出错
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options.applyid)
    // this._qualificateData(options.pid)
      wx.setNavigationBarTitle({
        title: '资格信息'
      })
      this._qualificateApplyDetail(options.applyid)

      // this.setData({
      //   title: options.title,
      //   userName: options.userName,
      //   userId: options.uid,
      //   hasSkuQualificate: options.hasSkuQualificate,
      //   pid: options.pid
      // })
    if (options.arr) {
      this.setData({
        imgUrl: JSON.parse(options.arr)
      })
    }
    if (options.qualificateIds) {
      this.setData({qualificateIds: options.qualificateIds})
    }
    if (options.remark) {
      this.setData({remark: options.remark})
    }
    if (options.applyId) {
      this.setData({
        applyId: options.applyId
      })
      this._qualificateApplyDetail(options.applyId)
    }

    if (options.hasOwnProperty('type')) { //需要当前页提交 我的--页面进去的
      this.setData({
        send: options.hasOwnProperty('type')
      })
    }
    let pages = getCurrentPages();
    this.prevPage = pages[pages.length - 2]; // 上个页面
  },
  onShow() {
    // if (this.data.send) {//单页面进入
    // } else { // 详情页进入
    //   let { matchSkuList, select, bindIndex } = this.prevPage.data
    //   if (matchSkuList[select].matchSkuFormList.length>0) {//是否需要填写其它项
    //     let u = matchSkuList[select].selectedUser[bindIndex] // 当前用户数据
    //     this.setData({ matchFormList: deepClone(u.hasOwnProperty('matchFormList') ? u.matchFormList : matchSkuList[select].matchSkuFormList) })
    //     //如果没有设置过用户填写项则为默认数据，否则为用户填写的数据
    //   }
    // }
  },
  _qualificateApplyDetail(id){
    qualificateApplyDetail(id).then(res=>{
      console.log(res)
      let {failDesc,qualificateName,userName,userId,participantId,imageList,status,qualificateId,applyId}=res.data
      this.setData({
        failDesc: failDesc,
        title: qualificateName,
        userName: userName,
        userId: userId,
        pid: participantId,
        imgUrl:imageList,
        hasSkuQualificate:status,
        qualificateIds:qualificateId,
        applyId:applyId
      })
    })
  },
  chooseImage(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.src, // 当前显示图片的http链接  
      urls: this.data.imgUrl // 需要预览的图片http链接列表  
    })
  },
  addImage() { // 选择图片
    let _this = this;
    let {count,imageList} = this.data
    wx.chooseImage({
      count: count - imageList.length, // 可用数-当前数
      success: res => {
        _this.setData({
          imageList: [...imageList, ...res.tempFilePaths]
        })
        res.tempFilePaths.forEach(e => {
          _this._uploadFile(e)
        })
      }
    })
  },
  // 文件上传
  _uploadFile(img) {
    uploadFile(img, 'file', res => { // 图片上传成功
      res.data = JSON.parse(res.data)
      if (res.data.code != 0) {
        this.showToast('图片上传失败', 'none')
      } else {
        this.setData({
          ['imgUrl[' + this.data.imgUrl.length + ']']: res.data.url
        })
      }
      this.check()
    }, err => { // 图片上传失败
      this.showToast('图片上传失败', 'none')
      this.check()
    })
  },
  getCompData(e) { //获取子组件设置的值
    this.setData({ changeDataNow:true,['matchFormList[' + e.detail.formIndex + ']']: e.detail.inputObj})
    let { matchSkuList, select, bindIndex } = this.prevPage.data
    let { matchFormList } = this.data
    let obj = matchSkuList[select].selectedUser[bindIndex]
    if (matchFormList != '') { // 需要有动态表单项，则提交
      obj.matchFormList = matchFormList
    }
    this.prevPage.setData({ ['matchSkuList[' + select + '].selectedUser[' + bindIndex + ']']: obj })
    // setTimeout(()=>{ 
      this.setData({ changeDataNow: false })
    // },1000)
  },
  delImage(e) { // 删除图片
    let index = e.currentTarget.dataset.index;
    wx.showModal({
      title: '删除图片',
      content: '确定要删除第' + Number(index + 1) + '张图片？',
      showCancel: true, //是否显示取消按钮
      cancelText: "否", //默认是“取消”
      cancelColor: '#1781FF', //取消文字的颜色
      confirmText: "是", //默认是“确定”
      confirmColor: '#1781FF', //确定文字的颜色
      success: res => {
        if (!res.cancel) {
          //点击确定
          let {imageList,imgUrl} = this.data
          imageList.splice(index, 1)
          imgUrl.splice(index, 1)
          this.setData({
            imageList,
            imgUrl
          })
        }
      }
    })
  },

  //数据验证
  check() {
    let { imgUrl} = this.data
    if (imgUrl.length <= 0) {
      this.setData({
        sendState: 2
      })
    } else {
      this.setData({
        sendState: 0
      })
    }
  },

  //提交认证信息
  send() {
    let { send, matchFormList, imgUrl, changeDataNow,hasSkuQualificate} = this.data;
    let message={title:'',icon:'none'}
    if (send) { // 需要当前页提交
      if (imgUrl.length == 0) {
        message.title='请至少上传1张图片'
      } else {
        let { applyId, pid, imgUrl, qualificateIds } = this.data;
        let obj = {
          participantId: pid,
          qualificateId: qualificateIds,
          imageList: imgUrl
        }
        if (applyId != '') {
          obj.applyId = applyId
        }
        qualificateApply(obj).then(res => {
          if (res.code == 0) {
            message.title = '已提交'
            message.icon = 'success'
            setTimeout(() => {
              if (qualificateIds == '') {
                wx.navigateTo({ url: '/pages/state_page/index?pid=' + pid })
              } else {
                wx.navigateBack()
              }
            }, 2000)
          } else {
            message.title = res.msg
          }
        })
      }
    }
    if (message.title != ''){
      wx.showToast(message)
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})